<template>
  <view class="my-settle-wrapper">
    <radio
      class="settle-radio"
      :checked="checkedAll"
      color="#c00000"
      @click="radioClickHandler"
    >
      全选
    </radio>

    <view class="settle-total-price">
      <view class="price-left">合计:</view>
      <view class="price-right">￥{{ totalPrice }}</view>
    </view>

    <view class="settle-btn" @click="settlement">结算({{ checkedCount }})</view>
  </view>
</template>

<script>
import { mapGetters, mapMutations, mapState } from "vuex";
export default {
  name: "my-settle",
  props: {},
  data() {
    return {
      second: 3, // 倒计时秒数
    };
  },
  computed: {
    ...mapGetters("m_cart", ["checkedCount", "totalPrice", "total"]),
    ...mapGetters("m_user", ["addressStr"]),
    ...mapState("m_user", ["token"]),
    ...mapState("m_cart", ["cart"]),
    checkedAll() {
      return this.checkedCount === this.total;
    },
  },
  methods: {
    ...mapMutations("m_cart", ["checkedAllState"]),
    ...mapMutations("m_user", ["updateRedirectInfo"]),
    // 全选控制器
    radioClickHandler() {
      this.checkedAllState(!this.checkedAll);
    },
    // 结算按钮
    settlement() {
      if (!this.checkedCount) return uni.$showMessage("请选择要结算商品");

      if (!this.addressStr) return uni.$showMessage("请选择收货地址");

      // if (JSON.stringify(this.token) === "{}")
      //   return uni.$showMessage("请登录");
      if (JSON.stringify(this.token) === "{}") return this.navigatorTologin();

      this.payOrder();
    },
    // 倒计时功能
    showTips(n) {
      uni.showToast({
        icon: "none",
        mask: true,
        title: "请登录后再结算，" + n + "秒后自动跳转到登录界面",
        duration: 1500,
      });
    },
    // 登录跳转
    navigatorTologin() {
      this.second = 3;
      this.showTips(this.second);

      this.timer = setInterval(() => {
        this.second--;
        if (this.second <= 0) {
          clearInterval(this.timer);

          uni.switchTab({
            url: "/pages/my/index",
            success: () => {
              this.updateRedirectInfo({
                openType: "switchTab",
                from: "/pages/cart/index",
              });
            },
          });
          return;
        }
        this.showTips(this.second);
      }, 1000);

      // uni.switchTab({url: '/pages/my/index'})
    },
    // 订单支付
    async payOrder() {
      const orderInfo = {
        order_price: 0.01,
        consignee_addr: this.addressStr,
        goods: this.cart
          .filter((x) => x.goods_state)
          .map((x) => ({ goods_id: x.goods_id, goods_number: x.goods_count, goods_price: x.goode_price })),
      };

      // 订单创建
      const res = await uni.$http.post('/api/public/v1/my/orders/create', orderInfo)
      // if(res.data.meta.status !== 200) uni.$showMessage('订单创建失败')
      const orderNumber = res.data.message.order_number

      // 订单预支付
      const res2 = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {order_number: orderNumber})
      // if(res2.data.meta.status !== 200) uni.$showMessage('订单预支付失败')
      const payInfo = res2.data.message.pay

      // 订单支付
      const [err, succ] = await uni.requestPayment(payInfo)
      if(err) return uni.$showMessage('订单未支付')

      // 查看订单状态
      const res3 = await uni.$http.post('/api/public/v1/my/orders/chkOrder', {order_number: orderNumber})
      // if(res3.data.meta.status !== 200) uni.$showMessage('订单未支付')
      uni.showToast({
        title: '支付完成',
        icon: 'success'
      })

    },
  },
  watch: {},

  // 组件周期函数--监听组件挂载完毕
  mounted() {},
  // 组件周期函数--监听组件数据更新之前
  beforeUpdate() {},
  // 组件周期函数--监听组件数据更新之后
  updated() {},
  // 组件周期函数--监听组件激活(显示)
  activated() {},
  // 组件周期函数--监听组件停用(隐藏)
  deactivated() {},
  // 组件周期函数--监听组件销毁之前
  beforeDestroy() {},
};
</script>

<style scoped lang="scss">
.my-settle-wrapper {
  width: 100%;
  height: 50px;
  position: fixed;
  bottom: 0;
  left: 0;
  background-color: #fff;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  padding: 0 5px;
  box-sizing: border-box;

  .settle-total-price {
    display: flex;
    flex-direction: row;
    .price-right {
      color: #c00000;
      font-weight: bold;
    }
  }

  .settle-btn {
    background-color: #c00000;
    color: #e7e7e7;
    padding: 0 30px;
    height: 50px;
    line-height: 50px;
  }
}
</style>